#pragma once

#include <iostream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <functional>
#include "Log.hpp"

uint16_t defaultport = 8888;
std::string defaultip = "0.0.0.0";
const size_t size = 1024;
Log lg;

typedef std::function<std::string(const std::string &)> func_t;

enum
{
    SOCKET_ERR = 0,
    BIND_ERR
};

class UdpServer
{
public:
    UdpServer(const uint16_t &port = defaultport, const std::string &ip = defaultip)
        : _sockfd(0), _ip(ip), _port(port), _isrunning(false)
    {
    }

    void Init()
    {
        // 1. 创建udp socket
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            lg(Fatal, "ocket create error, sockfd: %d\n", _sockfd);
            exit(SOCKET_ERR);
        }
        lg(Info, "socket create success, sockfd: %d\n", _sockfd);
        // 2. bind socket
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_addr.s_addr = inet_addr(_ip.c_str());
        local.sin_port = htons(_port);

        if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            lg(Fatal, "bind error, errno: %d, err string: %s", errno, strerror(errno));
            exit(BIND_ERR);
        }
        lg(Info, "bind success, errno: %d, err string: %s", errno, strerror(errno));
    }

    void Run(func_t func)
    {
        _isrunning = true;
        char inbuffer[size];
        while (_isrunning)
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0, (struct sockaddr *)&client, &len);
            if (n < 0)
            {
                lg(Warning, "recvfrom error, errno: %d, err string: %s", errno, strerror(errno));
                continue;
            }
            inbuffer[n] = 0;
            std::string info = inbuffer;
            std::string echo_string = func(info);
            sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr *)&client, len);
        }


    }

    ~UdpServer() 
    {
         if(_sockfd>0) close(_sockfd);
    }

private:
    int _sockfd;     // 网路文件描述符
    std::string _ip; // 任意地址bind 0
    uint16_t _port;  // 表明服务器进程的端口号
    bool _isrunning;
};
